<script setup>
import {ref, nextTick, onUnmounted} from "vue";
import {readExcel} from "@/utils/readExcel";
import {exportWeek} from "./exportWeek";
import useReportStore from "@/stores/useReportStore";
import constants from "@/utils/constants";
import {uploadReport} from "../../utils/uploadReport";
import {fileToBuffer} from "../../utils/readExcel";
import {downloadOssCount, downloadOssFile, uploadOssFile} from "@/api/ossFile.js";

const fileList = ref([]);

async function uploadExcelReport(file) {
  await uploadReport(
      'baobiao',
      file.name,
      file
  )
  getTableData()
}

function handleRemove() {
  fileList.value = [];
}

async function getWeekReport(row) {
  loading.value = true
  downloadOssFile({path: row.path})
      .then(async (data) => {
        let file = new window.File([data], row.path.split("/")[2].split(".")[0], {
          type: row.path.split("/")[2].split(".")[1]
        });
        let sheet = await readExcel(file);
        await exportWeek(sheet);
      })
      .catch((e) => {
        console.log(e);
        ElMessage.error(e);
      })
      .finally(() => {
        loading.value = false;
      });
}

//分页相关
const activeName = ref("baobiao");
const loading = ref(false);
const tableData = ref([]);
const pagination = ref({
  pageSize: 10,
  total: 0,
  currentPage: 1
});

function getPagination(list, pageSize, currentPage) {
  pagination.value.total = list.length;
  let dataSource = [];
  if (list.length < pageSize) {
    //判断当前获取的接口数据的长度是否大于设置的展示个数（总页数是否大于1）
    const index = (currentPage - 1) * pageSize;
    dataSource = list.slice(index, pageSize); //截取当页展示数据
  } else if (currentPage === Math.ceil(list.length / pageSize)) {
    //当前页码是否为最后一页
    const index = (currentPage - 1) * pageSize;
    dataSource = list.slice(index);
  } else {
    /**
     * 若总页数大于1，且当前页码不是最后一页时
     * 获取下标（index）截取数据（dataSource）
     */
    const index = (currentPage - 1) * pageSize;
    dataSource = list.slice(index, currentPage * pageSize);
  }
  return dataSource;
}

function getTableData() {
  nextTick(() => {
    tableData.value = getPagination(
        useReportStore().report[activeName.value].toReversed(),
        pagination.value.pageSize,
        pagination.value.currentPage
    );
  });
}

function getCount() {
  loading.value = true;
  downloadOssCount({username: constants.username})
      .then((data) => {
        if (data) {
          console.log(data)
          useReportStore().setReport(JSON.parse(data.blob));
          tableData.value = useReportStore().report.baobiao;
          getTableData();
        } else {
          let data = {
            fileName: "count.json",
            fileBuffer: JSON.stringify({baobiao: [], weekly: [], daily: [], monthly: []}),
            user: constants.username,
            type: "count"
          };
          uploadOssFile(data).then(() => {
            getTableData()
          })
        }
      })
      .catch((e) => {
        ElMessage.error(e);
        console.log(e);
      })
      .finally(() => {
        loading.value = false;
      });
}

getCount();

//下载文件
function downloadFile(row) {
  downloadOssFile({path: row.path, type: "download"})
      .then((data) => {
        // 将 ArrayBuffer 转换为 Blob 对象
        const blob = new Blob([data], {
          type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
        });
        saveAs(blob, row.path.split("/")[2]);
      }).catch(e => {
    ElMessage.error(e)
    console.log(e)
  })

}
</script>

<template>
  <div v-loading="loading" class="body">
    <div class="header">
      <el-tabs v-model="activeName" @tab-click="getTableData">
        <el-tab-pane label="报表" name="baobiao"></el-tab-pane>
        <el-tab-pane label="周报" name="weekly"></el-tab-pane>
      </el-tabs>
      <div class="flex" v-if="activeName === 'baobiao'">
        <el-upload
            v-model:file-list="fileList"
            action=""
            :on-remove="handleRemove"
            :before-upload="uploadExcelReport"
        >
          <el-button type="primary">上传报表</el-button>
        </el-upload>
      </div>
    </div>

    <el-table ref="tableRef" :data="tableData">
      <el-table-column label="文件" prop="originName"></el-table-column>
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button
              link
              type="primary"
              @click="getWeekReport(row)"
              v-if="activeName === 'baobiao'"
          >生成周报
          </el-button>
          <el-button link @click="downloadFile(row)">下载</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="footer">
      <div/>
      <el-pagination
          background
          v-model:current-page="pagination.currentPage"
          layout="prev, pager, next"
          :total="pagination.total"
          :page-size="pagination.pageSize"
          @current-change="getTableData"
      />
    </div>

    <div id="echart"></div>
  </div>
</template>

<style scoped lang="scss">
#echart {
  width: 550px;
  height: 330px;
  display: none;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.outer {
  padding: 8px;
}

.flex {
  display: flex;
  gap: 4px;
}

.body {
  height: 100vh;
  padding: 12px;
  box-sizing: border-box;
}

.footer {
  display: flex;
  justify-content: space-between;
  position: absolute;
  bottom: 8px;
  right: 8px;
}
</style>
